<?php
namespace Admin\Controller;
use Think\Controller;
use Admin\Controller\CommonController;

class AuthController extends CommonController {
	/**
	 * 后台用户列表
	 * @return [type] [description]
	 */
	public function index() {
        $userName = I('get.username', '');
        $map = array();
        if($userName) {
            $map['username'] = $userName;
        }

        $adminModel = M('Admin');
        $total = $adminModel->where($map)->count();
        $page = new \Think\Page($total, 25);
        $show = $page->show();

        $adminList = $adminModel->where($map)
                     ->limit($page->firstRow .',' . $page->listRows)
                     ->select();

        $roles = M('AdminRole')->select();

        $channelList = M('Channel')->field('chid, name')->select();

        $this->assign('showpage', $show);
        $this->assign('roles', $roles);
        $this->assign('adminList', $adminList);
        $this->assign('channelList', $channelList);
		$this->display();
	}

	/**
	 * 添加用户
	 */
	public function addUser() {
		if(IS_POST) {
			$adminModel = D('Admin');
			if($adminModel->create($_POST, 4)) {
				$rights = M('AdminRole')->where(array('id' => $_POST['roleid']))->getField('auth');
				$dataGet = $_POST;
				$dataGet['adminauth'] = $rights;
				$dataGet['password'] = md5($dataGet['password']);
				$res = $adminModel->add($dataGet);
				if($res) {
					$this->success('添加成功');
				} else {
					$this->error('添加失败，请重试');
				}
			} else {
				$this->error($adminModel->getError());
			}

		} else {
			$this->error('非法操作');
		}
	}

	/**
	 * 编辑用户
	 * @return [type] [description]
	 */
	public function editUser() {
		if(IS_POST) {
			$adminModel = D('Admin');
			if(!$_POST['password'])
				unset($_POST['password']);

			if($adminModel->create($_POST, 4)) {
				$rights = M('AdminRole')->where(array('id' => $_POST['roleid']))->getField('auth');
				$dataGet = $_POST;
				$dataGet['adminauth'] = $rights;
				$_POST['password'] && $dataGet['password'] = md5($dataGet['password']);
				$res = $adminModel->save($dataGet);
				if($res !== false) {
					$this->success('修改成功');
				} else {
					$this->error('修改失败，请重试');
				}
			} else {
				$this->error($adminModel->getError());
			}

		} else {
			$this->error('非法操作');
		}
	}

	/**
	 * 删除后台用户
	 * @return [type] [description]
	 */
	public function ajaxDelUser() {
		if(IS_GET) {
			$id = I('get.id');
		} elseif(IS_POST) {
			$id = I('post.id');
			is_array($id) && $id = implode(',', $id);
		}

		if(empty($id)) {
			$message['status'] = -1;
			$message['msg'] = '选项不能为空';
			$this->ajaxReturn($message);
		}

		$map['id'] = array('in', $id);
		$res = M('Admin')->where($map)->delete();
		if($res) {
			$message['status'] = 1;
			$message['msg'] = '删除成功';
			$this->ajaxReturn($message);			
		} else {
			$message['status'] = -1;
			$message['msg'] = '删除失败，请重试';
			$this->ajaxReturn($message);
		}
	}


	/**
	 * ajax获取用户信息
	 * @param  integer $id [description]
	 * @return [type]      [description]
	 */
    public function ajaxGetUserInfo($id=0){
        $adminModel = M('Admin');
        if($id){
            $userinfo = $adminModel->where('id=' . $id)->find();
            if($userinfo){
                $this->ajaxReturn($userinfo);
            }else{
                $this->ajaxReturn(0);
            }
        }else{  
            return false;
        }
    }

	/**
	 * 通过用户ID获取用户权限
	 * @return [type] [description]
	 */
    public function getAuthByUser() {
    	$id = I('get.id', 0);
    	$authList = M('Admin')->where(array('id' => $id))->getField('adminauth');
    	$this->_authTree($authList);
    }

    /**
     * 设置用户自身权限
     * @return [type] [description]
     */
    public function ajaxSetUserAuth() {
 		$idList=I("get.idList");
        $regx='/^\d+$/';
        foreach(explode(",",$idList) as $v){
            preg_match($regx, $v, $a);
            if(count($a) >= 1){
                $arr[]=$v;
            }
        }

        $idList = implode(",", $arr);

        $a = M('Admin')->save(array(
            'adminauth' => $idList,
            'id' => I("get.id"),
        ));
        $this->ajaxReturn($a);   	
    }

	/**
	 * 后台用户列表
	 * @return [type] [description]
	 */
	public function role() {
        $name = I('get.name', '');
        $map = array();
        if($name) {
            $map['name'] = $name;
        }

        $roleModel = M('AdminRole');
        $total = $roleModel->where($map)->count();
        $page = new \Think\Page($total, 25);
        $show = $page->show();

        $roleList = $roleModel->where($map)
                     ->limit($page->firstRow .',' . $page->listRows)
                     ->select();

        $this->assign('showpage', $show);             
        $this->assign('roleList', $roleList);
		$this->display();
	}

	/**
	 * 添加角色
	 */
	public function addRole() {
		if(IS_POST) {
			$roleModel = D('AdminRole');
			if($roleModel->create()) {
				$res = $roleModel->add();
				if($res) {
					$this->success('添加成功');
				} else {
					$this->error('添加失败，请重试');
				}
			} else {
				$this->error($roleModel->getError());
			}

		} else {
			$this->error('非法操作');
		}		
	}

	/**
	 * 修改该角色
	 */
	public function editRole() {
		if(IS_POST) {
			$roleModel = D('AdminRole');
			if($roleModel->create()) {
				$res = $roleModel->save();
				if($res !== false) {
					$this->success('修改成功');
				} else {
					$this->error('修改失败，请重试');
				}
			} else {
				$this->error($roleModel->getError());
			}

		} else {
			$this->error('非法操作');
		}		
	}


	/**
	 * 删除角色
	 * @return [type] [description]
	 */
	public function ajaxDelRole() {
		if(IS_GET) {
			$id = I('get.id');
		} elseif(IS_POST) {
			$id = I('post.id');
			is_array($id) && $id = implode(',', $id);
		}

		if(empty($id)) {
			$message['status'] = -1;
			$message['msg'] = '选项不能为空';
			$this->ajaxReturn($message);
		}

		$map['id'] = array('in', $id);
		$res = M('AdminRole')->where($map)->delete();
		if($res) {
			$message['status'] = 1;
			$message['msg'] = '删除成功';
			$this->ajaxReturn($message);			
		} else {
			$message['status'] = -1;
			$message['msg'] = '删除失败，请重试';
			$this->ajaxReturn($message);
		}
	}

	/**
	 * ajax获取用户信息
	 * @param  integer $id [description]
	 * @return [type]      [description]
	 */
    public function ajaxGetRoleInfo($id=0){
        $roleModel = M('AdminRole');
        if($id){
            $roleinfo = $roleModel->where('id=' . $id)->find();
            if($roleinfo){
                $this->ajaxReturn($roleinfo);
            }else{
                $this->ajaxReturn(0);
            }
        }else{  
            return false;
        }
    }
        
	/**
	 * 通过角色ID获取用户权限
	 * @return [type] [description]
	 */
    public function getAuthByRole() {
    	$id = I('get.id', 0);
    	$authList = M('AdminRole')->where(array('id' => $id))->getField('auth');
    	$this->_authTree($authList);
    }


    /**
     * 设置用户自身权限
     * @return [type] [description]
     */
    public function ajaxSetRoleAuth() {
 		$idList=I("get.idList");
        $regx='/^\d+$/';
        foreach(explode(",",$idList) as $v){
            preg_match($regx, $v, $a);
            if(count($a) >= 1){
                $arr[]=$v;
            }
        }

        $idList = implode(",", $arr);

        $a = M('AdminRole')->save(array(
            'auth' => $idList,
            'id' => I("get.id"),
        ));
        $this->ajaxReturn($a);   	
    }

    public function ajaxGetLiveAuth() {
    	$id = I('get.id', 0);
    	$liveAuth = M('Admin')->where(array('id' => $id))->getField('liveauth');
		$channelList = M('Channel')->field('chid, name')->select();
		$authlist = explode(",", $liveAuth);

        $arr['id'] = 0;
    	$arr['item'] = array();

        foreach($channelList as $k=>$v){
        	$arr['item'][$k] = array('id'=> $v['chid'], 'text' => $v['name']);
        	if(in_array($v['chid'], $authlist)){
				$arr['item'][$k]['checked'] = "1";
        	}
        }
        $this->ajaxReturn($arr);
    }


    /**
     * 设置用户自身权限
     * @return [type] [description]
     */
    public function ajaxSetUserLiveAuth() {
 		$idList=I("get.idList");
        $regx='/^\d+$/';

        foreach(explode(",",$idList) as $v){
            preg_match($regx, $v, $a);
            if(count($a) >= 1){
                $arr[]=$v;
            }
        }

        $idList = implode(",", $arr);

        $a = M('Admin')->save(array(
            'liveauth' => $idList,
            'id' => I("get.id"),
        ));
        $this->ajaxReturn($a);   	
    }

    /**
     * 权限菜单
     * @param  string $authlist [description]
     * @return [type]           [description]
     */
    protected function _authTree($authlist=""){
        $authlist = explode(",", $authlist);
        $adminAuthmodel = M('AdminAuth');
        $topAuthList = $adminAuthmodel->where(array("pid"=>0))->select();

        $arr['id']=0;
        $arr['item']=array();

        foreach($topAuthList as $k=>$v){
            $arr['item'][] = array('id'=>"T_" . $v['id'], 'child' => '1', 'text' => $v['name'], 'item'=>array());
            $secondeAuthList = $adminAuthmodel->where(array("pid" => $v['id']))->select();
            foreach($secondeAuthList as $kk => $vv){
                $arr['item'][$k]['item'][$kk] = array('id' => $vv['id'], 'text' => $vv['name']);
                if(in_array($vv['id'], $authlist)){
                    $arr['item'][$k]['item'][$kk]['checked'] = "1";
                }
            }
        }
        $this->ajaxReturn($arr);
    }
}